<template>
    <div class="my_index">
        <div class="pop">
            <div class="spinner">
                <div class="bounce1"></div>
                <div class="bounce2"></div>
                <div class="bounce3"></div>
            </div>
        </div>
        <div class="bacggroud_wraper"></div>
        <header class="top">
            <header class="vip">
                <section class="con">
                    <div class="header">
                        <div class="avatar">
                            <van-icon name="user-circle-o" size="1rem" color="#ddd" />
                            <!-- <img src="../static/common/header.png" alt="" /> -->
                        </div>
                    </div>
                    <div class="right">
                        <div class="right_up">
                            <div class="station"> </div>
                            <div class="grade"></div>
                        </div>
                        <div class="right_down">NO.</div>
                    </div>
                    <div class="scan"></div>
                </section>
                <div class="amount_container">
                    <div class="text">卡余额：<span class="amount">￥</span></div>
                    <span class="go_remit"> 充值 </span>
                </div>
            </header>
        </header>
        <div class="vip-center">
            <span class="integral_container">
                <div class="integral">积分：
                    <span class="value"></span>  
                    <van-icon name="arrow" />
                </div>
            </span>
            <span class="integral_container">
                <div class="integral">优惠劵：
                    <span class="value"></span>  
                    <van-icon name="arrow" />
                </div>
            </span>
        </div>
        <footer class="bottom">
            <div class="title">VIP 特权</div>
            <div class="cont">
                <span class="item" tag="div">
                    <div class="icon charge"></div>
                    <div class="text">我的订单</div>
                </span>
                <span class="item" tag="div">
                    <div class="icon consume"></div>
                    <div class="text">充值订单</div>
                </span>
                <span class="item" tag="div">
                    <div class="icon car"></div>
                    <div class="text">我的爱车</div>
                </span>
                <span class="item" tag="div">
                    <div class="icon svip"></div>
                    <div class="text">超级会员</div>
                </span>
                <div class="item" tag="div">
                    <div class="icon vip"></div>
                    <div class="text">会员卡</div>
                </div>
                <div class="item">
                    <div class="icon recommend"></div>
                    <div class="text">推荐有奖</div>
                </div>
                <span class="item" tag="div">
                    <div class="icon pay"></div>
                    <div class="text">支付设置</div>
                </span>
                <span class="item" tag="div">
                    <div class="icon fuel"></div>
                    <div class="text">油站导航</div>
                </span>

                <span class="item" tag="div">
                    <div class="icon remit"></div>
                    <div class="text">今日油价</div>
                </span>

                <span class="item" tag="div">
                    <div class="icon teamcard"></div>
                    <div class="text">我的车队</div>
                </span>
            </div>
            <div class="goApplet">
                <div class="item">
                    <div class="icon setting"></div>
                    <div class="text">快捷加油</div>
                </div>
            </div>
        </footer>
        <van-overlay>
            <div class="scan_wrapper">
                <div class="block">
                    <div class='title'>会员码</div>
                    <div style="text-align: center"> 用于识别会员身份，参与站内活动</div>
                    </qr>
                </div>
            </div>
        </van-overlay>
    </div>
</template>
  
<script>
import Vue from "vue";
import { Icon } from 'vant';
import { getAuthen } from "@/utils/getAuthen";
import querystring from "querystring";
import { mapMutations, mapActions } from "vuex";
import { getEnterpriseId } from "@/utils/getEnterpriseId";

Vue.use(Icon);

export default Vue.extend({
    head() {
        return {
            title: "我的",
        };
    },
    data() {
        return {
            redirect: "",
            tip: "认证中,请稍后...",
            mobilePhone: ''
        };
    },
    async created() {
        console.log('authMy----------')
        try {
            let type = 0;
            // 0 获取openid 常规流程
            // 1 用户第一次，网站直接跳转 获取phone 正常流程
            // 2 用户通过会员卡界面激活，有openId无activateTicket 可能没有outerStr 其他同1 特殊流程
            // 3 已经激活的用户，木有了缓存，二次进入 正常流程

            let state = this.$route.query.state; // 0
            let code = this.$route.query.code; // 0

            let outerStr = this.$route.query.outer_str; // 1

            let cardId = this.$route.query.card_id; // 1 2
            let openId = this.$route.query.openid; // 1 2 3
            let activateTicket = this.$route.query.activate_ticket; // 1 2
            let encryptCode = this.$route.query.encrypt_code; // 1 2



            let phone = this.$route.query.phone;// 3
            let unionId = this.$route.query.unionid;  // 3
            let originUrl = this.$route.query.originurl // 3

            let enterpriseId = "";

            let extStr = "";
            if (!!state) {
                extStr = state;
                type = 0;
            } else if (!!outerStr) {
                extStr = outerStr;
                type = 1;
            } else if (!!cardId && !activateTicket) {
                type = 2;
            } else if (!!phone) {
                type = 3
                extStr = originUrl
            }

            // 用户直接访问
            if (!state && !outerStr && !cardId && !phone) {
                this.tip = "此页不支持直接访问";
                return;
            }
            // 解析url
            const urlInfo = this.parseExtStr(extStr);

            console.log('authMy---解析路径：', urlInfo)
            console.log('authMy---state:', state)
            console.log('authMy---outerStr', outerStr)
            console.log('authMy---openId', openId)
            console.log('authMy---activateTicket', activateTicket)
            console.log('authMy---encryptCode', encryptCode)
            console.log('authMy---phone', phone)
            console.log('authMy---unionId', unionId)
            console.log('authMy---originUrl', originUrl)
            console.log('authMy---enterpriseId', enterpriseId)
            console.log('authMy---extStr', extStr)
            console.log("remitAuth---type", type);


            // 保存分享者id（用户通过推荐有奖分享出来的页面进来时，url会携带一个分享者的id，字段名叫userId）
            if (urlInfo.searchObj.shareUserId) {
                localStorage.setItem('shareUserId', urlInfo.searchObj.shareUserId)
            }

            if (type == 2) {
                //根据会员卡id拉取油企id 重定位跳转地址 
                const enterpriseIdPro = await this.queryEnterpriseIdByCardId(cardId);
                enterpriseId = enterpriseIdPro.enterpriseId;
                this.redirect = "/" + enterpriseId + "/my/";

                // const phoneRes = await this.getPhoneByAuthenInfo(enterpriseId);
                // phone = phoneRes.phone;
                // unionId = phoneRes.unionId;


                // this.$store.commit("authen/setEnterpriseId", enterpriseId)
                // this.$store.commit("authen/setOpenId", openId)
                // this.$store.commit("authen/setPhone", phone)
                // this.$store.commit("authen/setUnionId", unionId)

                // this.handleGotoPage()
            } else {
                // 网址里面包含油企id，跳转网址在urlInfo里
                enterpriseId = urlInfo.enterpriseId;
                // 充值界面特殊处理
                if (urlInfo.firstUrl == "/charge/") {
                    enterpriseId = urlInfo.searchObj.enterpriseId;
                } else if (urlInfo.firstUrl == "/plus/") {
                    enterpriseId = urlInfo.searchObj.enterpriseId;
                }

                this.redirect = urlInfo.fullUrl;
            }
            // 没有油企id，强退
            if (!enterpriseId) {
                this.tip = "请访问站点网站";
                return;
            }

            if (type == 0) {
                // openid 认证 回来 -> 开始手机认证
                const openIdRes = await this.queryOpenIdByEnterpriseId(enterpriseId);
                const openId = openIdRes.openId;
                console.log("authMy---存了openId" + openId);
                this.$store.commit("authen/setEnterpriseId", enterpriseId)
                this.$store.commit("authen/setOpenId", openId)

                if(openIdRes.retCode && openIdRes.retCode===600){
                    alert("1001,拉取openId失败,请重试~")
                    localStorage.clear() // 清空一下缓存
                    sessionStorage.clear()
                }else{
                     getAuthen(extStr);
                }
                return

            } else if (type == 1 || type == 2) {
                // type == 1  正常流程
                const phoneRes = await this.getPhoneByAuthenInfo(enterpriseId);
                phone = phoneRes.phone;
                unionId = phoneRes.unionId;



                this.$store.commit("authen/setEnterpriseId", enterpriseId)
                this.$store.commit("authen/setOpenId", openId)
                this.$store.commit("authen/setPhone", phone)
                this.$store.commit("authen/setUnionId", unionId)



                this.handleGotoPage()
            } else if (type == 3) {
                this.$store.commit("authen/setEnterpriseId", enterpriseId)
                this.$store.commit("authen/setOpenId", openId)
                this.$store.commit("authen/setPhone", phone)
                this.$store.commit("authen/setUnionId", unionId)

                this.handleGotoPage()
            }

        } catch (err) {
            console.log(err)
            const message = !!err.message ? err.message : err
            alert(message)
        }

        // this.getAppId(id).then(()=>{
        //   this.getPhoneByAuthenInfo();
        // }).catch((res)=>{
        //   alert("拉取appId失败")
        // })
    },
    methods: {
        test() {
            window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxab62cad69f646815&redirect_uri=https%3A%2F%2Fyh.xailife.com%2Fcash-register%2Fpages%2Fcash%2Findex%3Ffmno%3D301015200001138%26clientSerialNo%3D111111%26platform%3D2&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
        },
        parseExtStr(extStr) {
            let searchObj;
            let searchStr;
            let enterpriseId;

            const [url, str] = extStr.split(".");
            if (str !== undefined) {
                searchStr = str.replace(/-/g, "&").replace(/_/g, "=");
                searchObj = querystring.parse(searchStr);
            } else {
                searchStr = "";
                searchObj = {};
            }

            let enterpriseIdArr = url.replace(/\//, "").match(/^\d{1,}/);
            if (enterpriseIdArr == null) {
                enterpriseId = "";
            } else {
                enterpriseId = enterpriseIdArr[0];
            }

            return {
                fullUrl: url + (searchStr != "" ? "?" : "") + searchStr,
                firstUrl: url,
                searchObj,
                enterpriseId,
            };
        },
        async getUserInfo() {
            console.log("手机号getUserInfo" + this.phone)
            try {
                const infoData = await this.$axios.$get("/selectMemberInfo", {
                    params: {
                        enterpriseId: this.enterpriseId,
                        mobilePhone: this.phone,
                    },
                });

                if (infoData.retCode !== 0) {
                    throw new Error(infoData.message);
                }
                if(!infoData.data){
                    localStorage.clear() // 清空缓存
                    throw new Error("1004,查询不到该用户信息，请重新进入");
                }
                this.setUserInfo(infoData.data)

                console.log(infoData.data);
            } catch (error) {
                alert(error);
            }
        },
        async handleGotoPage() {
            console.log('authMy----redirect', this.redirect)
            await this.getUserInfo();
            this.$router.replace({
                path: this.redirect,
            });
        },
        // havingOpenIdAuthen(enterpriseId,extStr) {
        //   // const appIdPro = await this.queryAppIdByEnterpriseId(enterpriseId);

        // },

        // 获取openId
        async queryOpenIdByEnterpriseId(enterpriseId) {
            const code = this.$route.query.code;
            const gzhAuthenRes = await this.$axios.$get("/getGzhAuthorizeInfo", {
                params: {
                    code,
                    enterpriseId: enterpriseId,
                },
            });
            if (gzhAuthenRes.retCode !== 0) {
                return Promise.reject({
                    message:"拉取openId失败",
                    retCode:600
                });
            }
            const openId = gzhAuthenRes.data.openid;
            console.log('拉取的openId为', openId);
            return Promise.resolve({
                enterpriseId,
                openId,
            });
        },

        // 根据enterpriseId 获取 phone
        async getPhoneByAuthenInfo(enterpriseId) {
            console.log('authMy---获取手机号了嘛----')
            // 获取分享者id
            let shareUserId = Number(localStorage.getItem('shareUserId'))
            const encryptCode = this.$route.query.encrypt_code;
            const openId = this.$route.query.openid;
            const activateTicket = this.$route.query.activate_ticket;

            if (!!enterpriseId && !!encryptCode && !!openId && !!activateTicket && false) {
                const gzhAuthenRes = await this.$axios.$post(
                    "/selectCardMobilePhone",
                    {
                        enterpriseId: enterpriseId,
                        openId: openId,
                        activateTicket: activateTicket,
                        encryptCode: encryptCode,
                    }
                );
                if (gzhAuthenRes.retCode !== 0) {
                    return Promise.reject("拉取手机号失败");
                }
                const phone = gzhAuthenRes.data.phone;
                const unionId = gzhAuthenRes.data.unionid;
                // commit("setOpenId", openId)
                // commit ("setPhone", phone)
                // commit ("setUnionId", unionId)
                return Promise.resolve({
                    phone,
                    unionId
                });
            } else if (!!enterpriseId && !!encryptCode && !!openId) {

                // 获取微信卡卷用户信息
                let gzhAuthenRes;
                if (shareUserId) {
                    // 如果存在shareUserId，则是通过分享链接进来
                    gzhAuthenRes = await this.$axios.$post(
                        "/selectWxMemberCardInfo",
                        {
                            enterpriseId: enterpriseId,
                            openId: openId,
                            encryptCode: encryptCode,
                            userId: shareUserId
                        }
                    );
                } else {
                    // 如果没有shareUserId ，则证明不是通过分享链接进来
                    gzhAuthenRes = await this.$axios.$post(
                        "/selectWxMemberCardInfo",
                        {
                            enterpriseId: enterpriseId,
                            openId: openId,
                            encryptCode: encryptCode,
                            // activateTicket: activateTicket,
                        }
                    );
                }

                if (gzhAuthenRes.retCode !== 0) {
                    return Promise.reject(gzhAuthenRes.message);
                }
                const phone = gzhAuthenRes.data.mobilePhone;
                const unionId = gzhAuthenRes.data.unionid;

                // ------------------临时测试使用的保存数据，最后记得这个保存可以去掉
                localStorage.setItem('selectWxMemberCardInfo44444', JSON.stringify(gzhAuthenRes))
                return Promise.resolve({
                    phone,
                    unionId,
                });
            } else {
                throw new Error("authen参数不全")
            }
        },

        // 根据cardId获取enterpriseId
        async queryEnterpriseIdByCardId(cardId) {
            const enterpriseIdPro = await this.$axios.$get("/selectEnterpriseIdByCardId", {
                params: {
                    cardId,
                },
            });
            if (enterpriseIdPro.retCode != 0) {
                return Promise.reject("拉取EnterpriseId失败");
            }
            return Promise.resolve({
                cardId: cardId,
                enterpriseId: enterpriseIdPro.data,
            });
        },

        // 通过enterpriseId 获取appId
        async queryAppIdByEnterpriseId(enterpriseId) {
            const appIdRes = await this.$axios.$get("/getStationGzhAppId", {
                params: {
                    enterpriseId,
                },
            });
            if (appIdRes.retCode != 0) {
                return Promise.reject("获取appid失败");
            }
            // commit("setAppId", appIdRes.data.appId)
            return Promise.resolve({
                enterpriseId,
                appId: appIdRes.data.appId,
            });
        },
        ...mapMutations({
            setEnterpriseId: "authen/setEnterpriseId",
            setAppId: "authen/setAppId",
            setTempEnterpriseId: "setTempEnterpriseId",
            setUserInfo: "authen/setUserInfo",
        }),
        // ...mapActions({
        //   getAppId: "authen/getAppId",
        // }),
    },
})
</script>
  
<style lang="scss" scoped>
.my_index {
    width: 100vw;
    box-sizing: border-box;

    .pop {
        position: absolute;
        left: 0;
        top: 0;
        width: 100vw;
        height: 100vh;
        background-color: #ccc;
        opacity: 0.3;
        z-index: 999;

        .spinner {
            margin: 40vh auto 0;
            width: 70px;
            text-align: center;
        }

        .spinner>div {
            width: 18px;
            height: 18px;
            background-color: black;

            border-radius: 100%;
            display: inline-block;
            -webkit-animation: sk-bouncedelay 1.4s infinite ease-in-out both;
            animation: sk-bouncedelay 1.4s infinite ease-in-out both;
        }

        .spinner .bounce1 {
            -webkit-animation-delay: -0.32s;
            animation-delay: -0.32s;
        }

        .spinner .bounce2 {
            -webkit-animation-delay: -0.16s;
            animation-delay: -0.16s;
        }

        @-webkit-keyframes sk-bouncedelay {

            0%,
            80%,
            100% {
                -webkit-transform: scale(0);
            }

            40% {
                -webkit-transform: scale(1);
            }
        }

        @keyframes sk-bouncedelay {

            0%,
            80%,
            100% {
                -webkit-transform: scale(0);
                transform: scale(0);
            }

            40% {
                -webkit-transform: scale(1);
                transform: scale(1);
            }
        }
    }

    .bacggroud_wraper {
        position: absolute;
        width: 100%;
        top: 0;
        height: 50vh;
        background-color: #1e201f;
        z-index: -1;
    }

    .top {
        padding: 0 0.35rem;
        margin-top: 0.5rem;

        .vip {
            width: 100%;
            padding: .2rem .32rem .1rem;
            box-sizing: border-box;
            background: url("../static/fuel/new/bg.png") no-repeat 0 0;
            background-size: 100% 100%;
            width: 6.8rem;
            height: 2.8rem;
            border-radius: 0.3rem;
            position: relative;

            >.con {
                display: flex;
                position: relative;

                .header {
                    margin-right: 0.3rem;

                    .avatar {
                        width: 1.04rem;
                        height: 1.04rem;
                        border-radius: 50%;

                        >img {
                            width: 100%;
                            height: 100%;
                        }
                    }
                }

                .right {
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;

                    .right_up {
                        display: flex;
                        align-items: baseline;

                        .station {
                            margin-top: 0.1rem;
                            font-weight: 500;
                            font-size: 0.35rem;
                            color: #fff;

                            .icon {
                                // background: url("../../static/vip/vipicon.png") no-repeat 0 0;
                                background-size: 100% 100%;
                                display: inline-block;
                                width: 0.25rem;
                                height: 0.25rem;
                            }
                        }

                        .grade {
                            height: 0.29rem;
                            margin: 0.12rem 0;
                            font-size: 0.24rem;

                            // color: #d9a85a;
                            // background: #1e201f;
                            img {
                                width: 0.6rem;
                                margin-left: 0.06rem;
                            }
                        }
                    }

                    .right_down {
                        font-size: 0.25rem;
                        color: #999999;
                    }
                }


                .scan {
                    width: 1rem;
                    height: 1rem;
                    position: absolute;
                    right: 0.06rem;
                    top: 0.1rem;
                    background: url("../static/fuel/new/scan_code.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .amount_container {
                width: 6.1rem;
                display: flex;
                align-items: center;
                justify-content: space-between;
                position: absolute;
                bottom: 20px;

                .text {
                    color: #999999;
                    font-size: 0.26rem;

                    .amount {
                        font-size: 0.36rem;
                        font-weight: bold;
                        color: #fff;
                    }
                }

                .go_remit {
                    margin-left: 0.14rem;
                    text-align: center;
                    font-size: 0.25rem;
                    width: 1rem;
                    border-radius: 0.3rem;
                    color: #ffdb8f;
                    height: 0.5rem;
                    line-height: 0.5rem;
                    background: rgba(255, 219, 143, 0.2);
                }
            }

            .vip_bottom {
                width: 100%;
                margin-top: 0.43rem;
                display: flex;
                justify-content: space-between;
                align-items: center;



                .no {
                    font-size: 0.25rem;
                    color: #fadc93;
                }
            }
        }
    }



    .vip-center {
        margin-top: 0.43rem;
        padding: 0 0.35rem;
        display: flex;
        justify-content: center;
        align-items: center;

        .integral_container {
            margin-left: 0.1rem;
            display: inline-block;
            flex: 1;

            &:first-child {
                border-right: 1px solid #666;
            }

            .integral {
                display: flex;
                align-items: center;
                justify-content: center;
                color: #666;
                font-size: 0.24rem;

                .value {
                    font-size: 0.35rem;
                    font-weight: 600;
                    color: #fff;
                }

                .van-icon {
                    color: #fff;
                    font-size: 0.35rem;
                }
            }
        }

        .no {
            font-size: 0.25rem;
            color: #fadc93;
        }
    }

    .bottom {
        width: 100%;
        margin-top: 0.5rem;
        min-height: calc(100vh - 2.30rem);
        box-sizing: border-box;
        background-color: #fff;
        padding: 0.5rem 0.35rem 1.2rem 0.35rem;
        border-radius: 0.3rem 0.3rem 0 0;

        // margin-top: 0.4rem;
        >.title {
            color: #404040;
            font-weight: bolder;
            font-size: 0.28rem;
        }

        >.cont {
            margin: 0 auto;
            margin-top: 0.4rem;
            display: flex;
            flex-wrap: wrap;
            align-content: space-between;


            .item {
                width: 1.2rem;
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-right: .65rem;
                margin-bottom: 0.64rem;

                .icon {
                    width: 0.8rem;
                    height: 0.8rem;
                    background-color: rgba(240, 210, 153, 100);
                    background-size: 100% 100%;
                    margin-bottom: 0.36rem;
                    border: 1px dashed #ddd;
                }

                .text {
                    height: 0.32rem;
                    color: rgba(87, 87, 87, 100);
                    font-size: 0.26rem;
                    text-align: center;
                }

                &:nth-child(4n) {
                    margin-right: 0;
                }
            }

            .item {
                .vip {
                    background: url("../static/fuel/new/vip.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .item {
                .charge {
                    background: url("../static/fuel/new/order.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .item {
                .car {
                    background: url("../static/fuel/new/love_car.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .item {
                .recommend {
                    background: url("../static/fuel/new/recommend.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .item {
                .svip {
                    background: url("../static/fuel/new/svip.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .item {
                .consume {
                    background: url("../static/fuel/new/charch.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .item {
                .pay {
                    background: url("../static/fuel/new/pay_setting.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .item {
                .fuel {
                    background: url("../static/fuel/new/station_navigation.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }


            .item {
                .remit {
                    background: url("../static/fuel/new/today_oilprice.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }

            .item {
                .teamcard {
                    background: url("../static/fuel/new/teamCard.png") no-repeat 0 0;
                    background-size: 100% 100%;
                }
            }


        }
    }

    .goApplet {
    margin: 0 auto;
    margin-top: 1rem;
    width: 6rem;
    height: 0.8rem;
    // background: linear-gradient(-67deg, #fdb816, #fb8b0a);
    border-radius: 0.4rem;
    text-align: center;
    font-size: 0.4rem;
    color: #ff4445;
    line-height: 0.8rem;
    border: 1px solid #ff4445;
    font-weight: bold;
  }

    .scan_wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;

        .block {
            width: 6rem;
            padding: 0.5rem 1rem 0.7rem 1rem;
            box-sizing: border-box;
            border-radius: 0.3rem;
            background-color: #fff;

            .title {
                font-size: 0.3rem;
                line-height: 0.3rem;
                text-align: center;
                margin-bottom: 0.3rem;
                font-weight: bold;
            }

            .qr {
                width: 100%;
            }
        }

    }
}
</style>
  